/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.dd.processbutton.utils;

/**
 * 动画工具类
 *
 * @since 2021-03-01
 */
public class AnimationUtils {
    private AnimationUtils() {
    }

    /**
     * 动画状态
     *
     * @since 2021-03-01
     */
    private static class AnimationState {
        boolean animationClockLocked;
        long currentVsyncTimeMillis;
        long lastReportedTimeMillis;
    }

    private static final ThreadLocal<AnimationState> ANIMATION_STATE
            = new ThreadLocal<AnimationState>() {
        @Override
        protected AnimationState initialValue() {
            return new AnimationState();
        }
    };

    /**
     * 当前动画时长
     *
     * @return 时长 ms
     */
    public static long currentAnimationTimeMillis() {
        AnimationState state = ANIMATION_STATE.get();
        if (state.animationClockLocked) {
            // It's important that time never rewinds
            return Math.max(state.currentVsyncTimeMillis,
                    state.lastReportedTimeMillis);
        }
        state.lastReportedTimeMillis = System.currentTimeMillis();
        return state.lastReportedTimeMillis;
    }
}
